﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class Manage_Emp3_Emp3 : AdminPageBase
{

    private string SearchWord;
    private string returnURL;
    private int SearchFlag;
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        if (!IsPostBack)
        {

            // 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "EmpId");
            this.GridView1.Attributes.Add("SortDirection", "ASC");
           // GridViewBind();
			getParam();
            if (SearchFlag ==1)
            {
                GridViewBind();
            }
            else
            {
	            DataTable dt = new DataTable();
	            dt.Columns.Add("EmpId");
	            dt.Columns.Add("CenterName");
	            dt.Columns.Add("CityName");
	            dt.Columns.Add("DeptName");
	            dt.Columns.Add("BrandName");
	            dt.Columns.Add("StoreCode");
	            dt.Columns.Add("Name");
	            dt.Columns.Add("Code");
	            dt.Columns.Add("JobName");
	            dt.Columns.Add("EntryDate", typeof(DateTime));
	            dt.Columns.Add("LeaveDate", typeof(DateTime));
	            dt.Columns.Add("");

	            GridviewControl.GridViewDataBind(this.GridView1, dt);
	            GridviewControl.ResetGridView(this.GridView1);
			}
            if (add == 1)
            {

                addEmp3.Enabled = true;
              
            }
            else
            {
                addEmp3.Enabled = false;
               
            }
         
        }
    }
    private void getParam()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["SearchWord"]))
        {
            SearchWord = Request.QueryString["SearchWord"];
            txtkeyword.Text = SearchWord;
        }
        if (!string.IsNullOrEmpty(Request.QueryString["SearchFlag"]))
            SearchFlag = Convert.ToInt32(Request.QueryString["SearchFlag"]);
       
    }

    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }
      
    }

    protected void GridViewBind()
    {

        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
       
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchEmp3(keyword,pager1.PageSize, pager1.CurrentPageIndex, sortExpression, sortDirection, int.Parse(AdminSessionHelper.UserDetails["UserId"].ToString()));
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
                //this.GridView1.DataSource = ds.Tables[0];
                //this.GridView1.DataBind();
                GridviewControl.GridViewDataBind(this.GridView1, ds.Tables[0]);
                pager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0]["qty"]);
                btnexport.Enabled = true;
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("EmpId");
                dt.Columns.Add("CenterName");
                dt.Columns.Add("CityName");
                dt.Columns.Add("DeptName");
                dt.Columns.Add("BrandName");
                dt.Columns.Add("StoreCode");
                dt.Columns.Add("Name");
                dt.Columns.Add("Code");
                dt.Columns.Add("JobName");
                dt.Columns.Add("EntryDate", typeof(DateTime));
                dt.Columns.Add("LeaveDate", typeof(DateTime));
                dt.Columns.Add("");
                GridviewControl.GridViewDataBind(this.GridView1, dt);
                pager1.RecordCount = 0;
                btnexport.Enabled = false;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            
        }

    }
  

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            Label lblEntryDate = (Label)e.Row.FindControl("lblEntryDate");
            Label lblLeaveDate = (Label)e.Row.FindControl("lblLeaveDate");
            e.Row.Cells[4].Attributes.Add("class", "text");
            e.Row.Cells[6].Attributes.Add("class", "text"); 
            if (lblEntryDate!=null && lblEntryDate.Text != "")
            {
                lblEntryDate.Text = Convert.ToDateTime(lblEntryDate.Text).ToShortDateString().Replace("1900/1/1", "");
            }
            if (lblLeaveDate != null && lblLeaveDate.Text != "")
            {
                lblLeaveDate.Text = Convert.ToDateTime(lblLeaveDate.Text).ToShortDateString().Replace("1900/1/1", "").Replace("2099/12/31", "");
            }
        }
      
    }
    protected void pager1_PageChanged(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
        this.GridView1.Attributes["SortDirection"] = sortDirection;

        this.GridViewBind();
    }



    protected void btnexport_Click(object sender, EventArgs e)
    {
      //  DataTable dt = GetExportData();
       // ExcelExport(GetStringWriter(dt), "内部员工.xls");

    DataTable dt = GetExportData();
       if (GridView1.Rows.Count == 1 && GridView1.Rows[0].Cells[0].Text ==GridviewControl.EmptyText)
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有数据，不需要导出吧！"), false);
        else
        {
            string style = @"<style> .text { mso-number-format:\@;color:#000000 } </style> ";

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("内部员工.xls", System.Text.Encoding.GetEncoding("utf-8")));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridView1.Columns[10].Visible = false;
            GridView1.AllowPaging = false;
            GridView1.AllowSorting = false;
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.RenderControl(htw);

            // Style is added dynamically
            Response.Write(style);

            Response.Write(sw.ToString());

            Response.End();
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }

    protected DataTable GetExportData()
    {
        DataTable dt = new DataTable();
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
       
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchEmp3(keyword,  pager1.PageSize, 0, sortExpression, sortDirection, int.Parse(AdminSessionHelper.UserDetails["UserId"].ToString()));
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                dt = ds.Tables[0];

            }
        }
        return dt;

    }
    protected void ExcelExport(StringWriter sw, string exportFileName)
    {

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.GetEncoding("utf-8")));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        // HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\" />");
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();


    }
    //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
    public static StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();

        //先写列的表头，这样保证如果没有数据也能输出列表头 
        sw.Write("所属指挥中心" + "\t ");
        sw.Write("城市" + "\t ");
        sw.Write("部门" + "\t ");
        sw.Write("所属品牌" + "\t ");
        sw.Write("所在店铺代码" + "\t ");
        sw.Write("员工姓名" + "\t ");
        sw.Write("员工号" + "\t ");
        sw.Write("职位" + "\t ");
        sw.Write("入职时间" + "\t ");
        sw.Write("离职时间" + "\t ");
        sw.Write("是否线已获得线上讲师资格" + "\t ");
        sw.Write("是否已完成线上讲师课程" + "\t ");
        sw.Write(sw.NewLine);

        //如果包含数据 
        if (dt != null)
        {
            //写数据 
            foreach (DataRow dr in dt.Rows)
            {
                sw.Write(dr["CenterName"].ToString() + "\t ");
                sw.Write(dr["CityName"].ToString() + "\t ");
                sw.Write(dr["DeptName"].ToString() + "\t ");
                sw.Write(dr["BrandName"].ToString() + "\t ");
                sw.Write(dr["StoreCode"].ToString() + "\t ");
                sw.Write(dr["Name"].ToString() + "\t ");
                sw.Write(dr["Code"].ToString() + "\t ");
                sw.Write(dr["JobName"].ToString() + "\t ");
                sw.Write(DateTime.Parse(dr["EntryDate"].ToString()).ToShortDateString() + "\t ");
                sw.Write(DateTime.Parse(dr["LeaveDate"].ToString()).ToShortDateString().Replace("1900/1/1","") + "\t ");
                sw.Write(dr["IsTeacherDesc"].ToString() + "\t ");
                sw.Write(dr["FinishClassDesc"].ToString() + "\t ");
                //换行 
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    }


    protected void addEmp3_Click(object sender, EventArgs e)
    {
	    int flag = 0;
        if (GridView1.Rows.Count > 0)
            flag = 1;
        returnURL ="Emp3.aspx?MenuId="+MenuId+"&SearchWord=" + txtkeyword.Text.Trim()+ "&SearchFlag=" +flag;
        Response.Redirect("Emp3Detail.aspx?returnURL=" + Server.UrlEncode(returnURL));
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
			int flag = 0;
        	if (GridView1.Rows.Count > 0)
            flag = 1;
        	returnURL ="Emp3.aspx?MenuId="+MenuId+"&SearchWord=" + txtkeyword.Text.Trim()+ "&SearchFlag=" +flag;
            Response.Redirect("Emp3Detail.aspx?id=" +e.CommandArgument.ToString()+"&returnURL="+Server.UrlEncode(returnURL));
        }
        else if (e.CommandName == "Delete")
        {
            int flag = 0;
            int id = Convert.ToInt32(e.CommandArgument.ToString());
          
            flag = jtDataAccess.OpEmp(JTDataAccess.OpType.Delete, id,"","",0,3,0,0,0,0,0,0,DateTime.Now,DateTime.Now,0,0);

            switch (flag)
            {

                case -1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该员工记录已经在使用，不允许删除！"), false);
                    break;
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                    break;
            }
       }
    }
    protected void btnInput_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuExcel.HasFile)
            {
                string fileType = fuExcel.FileName.Substring(fuExcel.FileName.LastIndexOf(".") + 1).ToUpper();

                if (fileType == "XLS" || fileType == "XLSX")
                {
                    DataTable dt = jtDataAccess.readExcelDataFromClient(fuExcel, "Sheet1", "Sheet1");
                    UserType ut = new UserType();//用户自定义类型
                    DataTable emp = ut.GetEmpTableType();
                    DataRow empRow;

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            empRow = emp.NewRow();
                            empRow["EmpTypeId"] =3;
                            empRow["Name"] = row["姓名"];
                            empRow["Code"] = row["员工号"];
                            empRow["CenterName"] = row["所属指挥中心"];
                            empRow["CityName"] = row["城市"];
                           // empRow["EmpTypeName"] = row["员工类别"];
                            //empRow["CustomerName"] = row["客户名称"];
                          //  empRow["CustomerCode"] = row["客户编号"];
                           // empRow["GradeName"] = row["职级"];
                            empRow["EntryDate"] = row["入职时间"];
                            empRow["LeaveDate"] = row["离职时间"];
                            empRow["DeptTypeName"] = row["部门类型"];
                            empRow["DeptName"] = row["部门"];
                            empRow["BrandName"] = row["所属品牌"];
                            empRow["StoreCode"] = row["所在店铺代码"];
                            empRow["JobName"] = row["职位"];
                            if (row[11].ToString() == "是")
                                empRow["IsTeacher"] = 1;
                            else
                                empRow["IsTeacher"] = 0;
                            if (row[12].ToString() == "是")
                                empRow["FinishClass"] = 1;
                            else
                                empRow["FinishClass"] = 0;
                            emp.Rows.Add(empRow);
                        }
                    }

                    emp.AcceptChanges();
                    int flag = jtDataAccess.ImportEmp3(emp);

                    switch (flag)
                    {
                        case -1:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("Excel文件中导入的员工编号有重复！"), false);
                            break;
                        case -2:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("导入的所属指挥中心、城市、部门类型、部门、所属品牌、所在店铺代码、姓名、员工号、职位、入职时间其中之一为空！"), false);
                         
                            break;
                        case 0:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有导入任何记录，请检查Excel文件！"), false);
                            break;
                        default:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(string.Format("成功导入{0}条记录", flag)), false);
                            GridViewBind();
                            break;
                    }
                }

            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
}